// 引入模块
const Sequelize = require('sequelize');
// 读取配置
const {mysql} = require('../../config/config.json');
const env = process.env.NODE_ENV;
const sqlConfig = mysql[env || 'production'];
// 根据配置实例化seq
var seq = new Sequelize(sqlConfig.dbname, sqlConfig.uname, sqlConfig.upwd, {
    host: sqlConfig.host,
    dialect: sqlConfig.dialect,
    pool: sqlConfig.pool
});

/**
 * 定义数据模型
 * 
 * @param {any} name 模型名称【数据库表名】
 * @param {any} attributes 数据字段集合
 * @returns 数据模型对象
 */
function defineModel (name, attributes) {
    var attrs = {};

    for (let key in attributes) {
        let value = attributes[key];
        if (typeof value === 'object' && value['type']) {
            value.allowNull = value.allowNull || false;
            attrs[key] = value;
        } else {
            attrs[key] = {
                type: value,
                allowNull: false
            };
        }
    }

    // 附加公共字段
    // attrs.id = {
    //     type: ID_TYPE,
    //     primaryKey: true
    // };
    
     // 调用seq的方法定义模型并返回
    return seq.define(name, attrs, {
        tableName: name,
        timestamps: false,
        hooks: {
            beforeValidate: function (obj) {
                let now = Date.now();
                if (obj.isNewRecord) {
                    obj.createAt = now;
                    obj.updateAt = now;
                    obj.version = 0;
                } else {
                    obj.updateAt = now;
                    ++obj.version;
                }
            }
        }
    });
}

exports.defineModel = defineModel;